<?php
/*
 * @Author: CHINAKAIYUAN<sunkaiyuan@namenode.cn>
 * @Date: 2022-02-04 16:53:56
 * @LastEditTime: 2023-11-03 15:08:06
 * @LastEditors: 孙开源 && sunkaiyuan@namenode.cn
 * @Description: 
 */

namespace App\Http\Services\Pro;


use App\Http\Services\Service;
use App\Models\MpcLocation;
use App\Repositories\ProOutsourcingFinishDetailRepository;
use App\Repositories\ProOutsourcingFinishRepository;

/**
 * @property ProOutsourcingFinishRepository $repository
 * @property ProOutsourcingFinishDetailRepository $details 
 * @method static ProOutsourcingFinishRepository save($data)
 * @method static ProOutsourcingFinishRepository delete($data)
 */
class OutsourcingFinishService extends Service
    {
    public function boot(
        ProOutsourcingFinishRepository $repository,
        ProOutsourcingFinishDetailRepository $details,
    ) {
        $this->repository = $repository;
        $this->details    = $details;
        }

    public function list()
        {
        return $this->details->condition(request())->getGrid();
        }
    public function info()
        {
        return $this->repository->condition(request())->getOne();
        }

    protected function save($data = null)
        {
        $data = $data ?? request()->toArray();
        //需要重新出库的
        $needReOutStorage = [];
        //不需要出库的
        $notNeedOutStorage = [];
        $location_id       = 0;

        $data['details'] = array_map(function ($v) use (&$notNeedOutStorage, &$needReOutStorage, $location_id)
            {
            if ($location_id == 0) {
                $location_id = $v['old_location_id'];
                }
            else {
                fail("一次只能回收一个库位的库存！");
                }

            // if (isset($v['id']) && is_numeric($v['id']) && $v['id'] > 0) {
            //     $item = $this->details->whereId($v['id'])->first();
            //     //数量不一致，需要重新占用！
            //     if ($item['quantity'] != $v['quantity']) {
            //         $needReOutStorage[] = $v['id'];
            //         }
            //     else {
            //         $notNeedOutStorage[] = $v['id'];
            //         }
            //     }
            $v['type_id'] = 3;
            return $v;
            }, $data['details']);

        $gdata = $this->repository->autosave($data);
        $gdata->details->filter(function ($v) use ($gdata)
            {
            $v->billdate = $gdata->billdate;
            $v->code     = $gdata->code;
            $v->save();
            });
        $this->saveCar($gdata);
        $this->saveCarry($gdata);
        return $gdata->details->pluck("id");

        }

    protected function audit($ids = null)
        {
        return $this->details->whereIn("id", $ids ?? $this->getRequestIds())->get()->filter(function ($v)
            {
            if ($v->status_id != 0) {
                fail("单据状态{$v->status->name}，审核失败！");
                }
            $v->mergeWhere(['location_id' => $v->old_location_id])
                ->setOutSoucing()
                ->useStorage("委外回收", "", null, null, "old_mpc_detail")
                ->subStorage("old_mpc_detail");
            $v->mergeWhere(['location_id' => $v->location_id])->addStorage("委外回收");
            return auditSave($v);
            });
        }

    protected function noaudit($ids = null)
        {
        $this->details->whereIn("id", $ids ?? $this->getRequestIds())->get()->filter(function ($v)
            {
            // dd($v->location_id);
            if ($v->status_id != 1) {
                fail("单据状态{$v->status->name}，反审失败！");
                }
            $v->nosubStorage("old_mpc_detail")->nouseStorage("old_mpc_detail");
            $v->noaddStorage();
            auditSave($v, false);
            });
        }
    private function saveCarry($model)
        {
        $model->details->filter(function ($row) use ($model)
            {
            if ($model->carry_id == $row->carry_id)
                return;
            else if ($row->carry_id > 0)
                $row->removeCarryItem();

            if ($model->carry_id > 0)
                $row->addCarryItem($model->carry_id, $row->main->code);

            });
        }
    private function saveCar($model)
        {
        $model->details->filter(function ($row) use ($model)
            {
            if ($model->car_id == $row->car_id)
                return;
            else if ($row->car_id > 0)
                $row->removeCarItem();
            if ($model->car_id > 0) {
                $row->addCarItem($row->old_location->name, $row->creator->department?->name ?? "染厂", $model->car_id);
                }
            });
        }

    protected function delete($codes = null)
        {
        $need_delete_product = $codes == null;
        $codes               = $codes ?? array_map(function ($v)
            {
            return $v['code'];
            }, request("removeRecords"));
        $ids                 = [];
        $this->repository->whereIn("code", $codes)->get()->filter(function ($v) use (&$ids)
            {
            if ($v->product)
                $ids[] = $v->product->id;
            $v->details->filter(function ($vv)
                {
                if ($vv->status_id == 1) {
                    fail("回收单状态{$vv->status->name}，反审失败！");
                    }
                $vv->delete();
                });
            $v->delete();
            });
        $need_delete_product && OutsourcingProductService::delete($ids);
        return $codes;
        }


    }